package com.xbn.netty.bioService;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author XBN
 * @date 2020/10/12 19:21
 * @email 78742541@qq.com
 */
public class BioService {
    /*
     * 测试请使用talnet  ip 6666端口发送内容，如果是本机 talnet 127.0.0.1  6666
     * */
    public static void main(String[] args) throws IOException {
        ThreadPoolExecutor myPoolExecutor = new ThreadPoolExecutor(50
                , 100,
                30, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(50000), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        ServerSocket serverSocket = new ServerSocket(6666);

        while (true)
        {
            //监听，等待客户端连接，如果没有得到客户端连接会在这里阻塞，什么事情都做不了
            System.out.println("等待连接");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            //创建一个线程与之通信
            myPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    //该线程
                    handler(socket);
                }
            });
        }
    }

    //该方法主要和客户端通信
    public  static  void handler(Socket socket){

        try {
            //byte数组用来接收数据
            byte[] bytes = new byte[1024];
            //通过socket来获取输入流
            InputStream inputStream = socket.getInputStream();
            //循环的读取客户端发送的数据
            while (true)
            {
                System.out.println("当前线程"+Thread.currentThread().getId());
                System.out.println("read....");
                //返回读了多少个数据，这里也会阻塞（bytes没有数据的情况下）
                int read = inputStream.read(bytes);
                if(read!=-1)
                {      //输出客户端发送的数据
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //关闭和client的连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}